package andev.schoolhelper.util;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;

import java.io.UnsupportedEncodingException;
import java.util.Map;

public class VolleyStringRequest extends StringRequest {
    private Listener<String> listener;
    private Map<String, String> headers;
    private Map<String, String> params;

    public VolleyStringRequest(int method, String url, Map<String, String> params, Listener<String> listener, ErrorListener errorListener) {
        super(method, url, listener, errorListener);
        this.listener = listener;
        this.params = params;
    }

    public VolleyStringRequest(int method, String url, Map<String, String> headers, Map<String, String> params, Listener<String> listener, ErrorListener errorListener) {
        super(method, url, listener, errorListener);
        this.listener = listener;
        this.headers = headers;
        this.params = params;
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

    @Override
    protected void deliverResponse(String response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        Log.i("SchoolHelper", "parseNetworkResponse");
        try {
            Log.i("SchoolHelper", "response=" + new String(response.data, "gb2312"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (String key : response.headers.keySet()) {
            Log.i("SchoolHelper", key + ":" + response.headers.get(key));
        }

        return super.parseNetworkResponse(response);
    }

    @Override
    public Map<String, String> getHeaders() {
        return headers;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        String paramBody = new String(super.getBody());
        paramBody = paramBody.substring(0, paramBody.length() - 1);
        return paramBody.getBytes();
    }
}
